import { useEffect, useState } from "react"
import { fetchDetailAPI, type DetailDataType } from "../../apis/detail"
import { useNavigate, useSearchParams } from "react-router-dom"
import { NavBar } from "antd-mobile"


const Detail = () => {
    // 状态变量
    const [detail, setDetail] = useState<DetailDataType | null>(null)

    // 获取路由参数
    const [params] = useSearchParams()
    const id = params.get('id')
    // 渲染数据
    useEffect(() => {
        const getDetailList = async () => {
            try {
                // ! 是 TypeScript 的非空断言操作符（Non-null Assertion Operator）
                const res = await fetchDetailAPI(id!)
                setDetail(res.data.data)
            } catch (error) {
                throw new Error('详情页数据获取失败')
            }
        }
        getDetailList()
    }, [id])

    // 路由跳转到上一页
    const navigate = useNavigate()
    const back = () => {
        navigate(-1)
    }

    // __html不能为undefined类型
    if(!detail){
        return <div>Loading...</div>
    }
    return (
        <>
            <NavBar onBack={back}>{detail?.title}</NavBar>
            {/* 内联HTML */}
            <div dangerouslySetInnerHTML={{ 
                __html: detail?.content 
            }}></div>
        </>
    )
}

export default Detail